package com.suwenhao.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.suwenhao.constants.Constant;
import com.suwenhao.entity.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @Author:suwenhao
 * @Description: 测试
 * @Date: Created in 2020/9/22 17:35
 */
@WebFilter("/*")
public class SysFilter extends HttpFilter {
    @Override
    public void destroy() {

    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String uri = request.getRequestURI();


        HttpSession session = request.getSession();


        if (uri.endsWith("/") || uri.endsWith("index.jsp")) {

            Cookie[] cookies = request.getCookies();

            //判断cookie不等于空
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String key = cookie.getName();
                    if (Constant.COOKIE_LOGIN.equals(key)) {
                        //判断cookie里面有登录信息

                        String value = cookie.getValue();

                        value = URLDecoder.decode(value, "UTF-8");

                        User user = JSONObject.parseObject(value, new TypeReference<User>() {
                        });

                        session.setAttribute(Constant.COOKIE_LOGIN, user);
                        session.setMaxInactiveInterval(30 * 60);


                        request.setAttribute("user", user);

                        request.getRequestDispatcher("/html/common/home.jsp").forward(request, response);
                        chain.doFilter(request, response);
                        return;

                    }
                }
            }

        } else if (uri.endsWith("login") ||
                uri.endsWith("/menu/listAll") ||
                uri.endsWith("/img/getImg")||
                uri.endsWith("forget.jsp")||
                uri.endsWith("forget")||
                uri.endsWith("/email/sendEmail")||
                uri.contains("wx")||
                uri.endsWith("/img/getPicCode")) {

        } else {
            //判断session是否有登录信息

            Object obj = session.getAttribute(Constant.SESSION_LOGIN);
            if (obj == null) {
                //非法登录  返回登录页面
                request.getRequestDispatcher("/index.jsp").forward(request, response);
                return;
            }


        }
        request.setAttribute("user", (User)session.getAttribute(Constant.SESSION_LOGIN));
        chain.doFilter(request, response);
    }
}
